debug = true;
angular.module('xqkj', ['ionic', 'ngCookies', 'ngResource', 'xqkj.controllers', 'xqkj.services', 'xqkj.directives', 'ionic.rating', 'ion-alpha-scroll', 'ngIOS9UIWebViewPatch', 'angularLazyImg', 'ionicLazyLoad', 'angularSpinners'])

.run(function($ionicPlatform, $rootScope, $ionicLoading, $http, $state, $ionicHistory, $interval, $ionicScrollDelegate, UserService, UtilsService, spinnerService) {
    $rootScope.root = $rootScope
    $rootScope.allwidth = window.innerWidth
    $ionicPlatform.ready(function() {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      // if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      //   cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      //   cordova.plugins.Keyboard.disableScroll(true);
      // }
      // if (window.StatusBar) {
      //   // org.apache.cordova.statusbar required
      //   StatusBar.styleLightContent();
      // }
    });


    $rootScope.loadCount = 0;

    $rootScope.$on('loading:show', function() {
      $ionicLoading.show({
          template: '<img src="img/horse.gif" style="width: 100%;padding: 0px;margin: 0px;border: 0px;height: auto;border-radius: 40px;">'
        })
        // spinnerService.show('all')
    });
    $rootScope.$on('loading:showMessage', function(event, args) {
      $ionicLoading.show({
        template: '<span style="line-height: 40px; font-size: 12px; min-height: 40px;">' + args.message + '</span>',
        noBackdrop: false,
        duration: 1500
      })
    });

    $rootScope.$on('loading:hide', function() {
      $ionicLoading.hide()
        // spinnerService.hide('all')
    })

    // $http.defaults.cache = CacheFactory('defaultCache', {
    //   maxAge: 15 * 60 * 1000, // Items added to this cache expire after 15 minutes
    //   cacheFlushInterval: 5 * 60 * 60 * 1000, // This cache will clear itself every hour
    //   deleteOnExpire: 'aggressive' // Items will be deleted from this cache when they expire
    // });


    var back = $interval(function() {
      try {
        var first = null;
        plus.key.addEventListener("backbutton", function() {
          //         alert( "BackButton Key pressed!" );
          console.log(angular.toJson($state.current));
          console.log(angular.toJson($state.current.name.indexOf('dash')));

          if ($state.current.name.indexOf('dash') < 0) {
            $ionicHistory.goBack();
            // alert( "BackButton Key pressed!" );
          } else {
            //首次按键，提示‘再按一次退出应用’
            if (!first) {
              $rootScope.$broadcast('loading:showMessage', {
                message: '再按一次退出'
              });
              first = new Date().getTime();
              setTimeout(function() {
                first = null;
              }, 1000);
            } else {
              if (new Date().getTime() - first < 1000) {
                plus.runtime.quit();
              }
            }
          }
        });

        $interval.cancel(back);
      } catch (e) {

      }
    }, 1000);

    // token存在登录
    if (UtilsService.isTokenExist()) {
      UserService.login({
        token: UtilsService.getToken()
      }).$promise.then(function(response) {
        UtilsService.clearCookie();

        if (UtilsService.isResponseOk(response)) {
          UtilsService.setToken(response.data.user.token);
          UtilsService.setUser(response.data.user);
        }
      });
    }


    // noop 保持session
    $interval(function() {
      UserService.noop();
    }, 8000);

    console.log(angular.toJson(UtilsService.getDist()));
    // console.log(angular.toJson(UtilsService.isDistExist()));
    console.log(angular.toJson(UtilsService.getUser()));
    $rootScope.dist = UtilsService.getDist()
    console.log(angular.toJson(UtilsService.getDist()));

    if (!$rootScope.dist) {
      $state.go('district.list');
      $rootScope.$broadcast('loading:showMessage', {
        message: '请选择小区'
      });
    }
    console.log(angular.toJson(UtilsService.getDist()));


    $rootScope.issb = navigator.userAgent.indexOf('Android 4.0') >= 0 || navigator.userAgent.indexOf('Android 4.1') >= 0 || navigator.userAgent.indexOf('Android 4.2') >= 0 ||  navigator.userAgent.indexOf('Android 4.3') >= 0
    console.log(navigator.userAgent)
    console.log(angular.toJson(UtilsService.getDist()));

  })
  .config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider, $httpProvider) {
    $ionicConfigProvider.tabs.position("bottom"); //Places them at the bottom for all OS
    $ionicConfigProvider.tabs.style("standard"); //Makes them all look the same across all OS
    $ionicConfigProvider.tabs.style("standard"); //Makes them all look the same across all OS
    $ionicConfigProvider.navBar.alignTitle('center');
    $ionicConfigProvider.backButton.previousTitleText(false);
    $ionicConfigProvider.backButton.text('');


    $httpProvider.defaults.timeout = 10000;
    $httpProvider.defaults.useXDomain = true;
    // 保持session 带sessionid
    $httpProvider.defaults.withCredentials = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];

    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';


    // post fix
    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */
    var param = function(obj) {
      var query = '',
        name, value, fullSubName, subName, subValue, innerObj, i;

      for (name in obj) {
        value = obj[name];

        if (value instanceof Array) {
          for (i = 0; i < value.length; ++i) {
            subValue = value[i];
            fullSubName = name + '[' + i + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        } else if (value instanceof Object) {
          for (subName in value) {
            subValue = value[subName];
            fullSubName = name + '[' + subName + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        } else if (value !== undefined && value !== null)
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }

      return query.length ? query.substr(0, query.length - 1) : query;
    };

    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function(data) {
      return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
    // angular.extend(CacheFactoryProvider.defaults, {
    //   maxAge: 3600000,
    //   deleteOnExpire: 'aggressive',
    //   onExpire: function(key, value) {
    //     var _this = this; // "this" is the cache in which the item expired
    //     angular.injector(['ng']).get('$http').get(key).success(function(data) {
    //       _this.put(key, data);
    //     });
    //   }
    // });

    // $ionicConfigProvider.scrolling.jsScrolling(false);
    $stateProvider
    // dash part
      .state('dash', {
        url: '/dash',
        abstract: true,
        contoller: 'DashCtrl',
        templateUrl: 'templates/dash.html'
      })
      .state('dash.home', {
        url: '/home',
        views: {
          'dash-home': {
            templateUrl: 'templates/dash/home.html',
            controller: 'DashHomeCtrl'
          }
        },
        params: {
          update: false
        }
      })
      .state('dash.class', {
        url: '/class',
        views: {
          'dash-class-left': {
            templateUrl: 'templates/dash/dash-class-left.html',
            // controller: 'DashClassCtrl'
          },
          'dash-class-right': {
            templateUrl: 'templates/dash/dash-class-right.html',
            // controller: 'DashClassCtrl'
          }
        }
      })
      .state('dash.form', {
        url: '/form',
        views: {
          'dash-form': {
            templateUrl: 'templates/dash/form.html',
            controller: 'DashFormCtrl'
          }
        }
      })
      .state('dash.cart', {
        url: '/cart',
        views: {
          'dash-cart': {
            templateUrl: 'templates/dash/cart.html',
            controller: 'DashCartCtrl'

          }
        }
      })
      .state('dash.mine', {
        url: '/mine',
        views: {
          'dash-mine': {
            templateUrl: 'templates/dash/mine.html',
            controller: 'DashMineCtrl'
          }
        }
      })

    // goods part
    .state('goods', {
        url: '/goods',
        abstract: true,
        controller: 'GoodsCtrl',
        templateUrl: 'templates/goods.html'
      })
      .state('goods.cursale', {
        url: '/cursale',
        templateUrl: 'templates/goods/cursale.html',
        controller: 'GoodsCursaleCtrl'
      })
      .state('goods.saledetail', {
        url: '/:id/saledetail',
        templateUrl: 'templates/goods/saledetail.html',
        controller: 'GoodsSaledetailCtrl'
      })
      .state('goods.detail', {
        url: '/:id',
        templateUrl: 'templates/goods/detail.html',
        controller: 'GoodsDetailCtrl'
      })
      .state('goods.search', {
        url: '/classid/:classid/type/:type',
        templateUrl: 'templates/goods/search.html',
        controller: 'GoodsSearchCtrl'
      })
      .state('goods.class', {
        url: '/class/:classid/type/:type',
        templateUrl: 'templates/goods/class.html',
        controller: 'GoodsClassCtrl'
      })
      .state('goods.comments', {
        url: '/:id/comments',
        templateUrl: 'templates/goods/comments.html',
        controller: 'GoodsCommentsCtrl'
      })

    // mine part
    .state('mine', {
        url: '/mine',
        abstract: true,
        templateUrl: 'templates/mine.html'
      })
      .state('mine.credit', {
        url: '/credit',
        templateUrl: 'templates/mine/credit.html',
        controller: 'MineCreditCtrl'
      })
      .state('mine.comment', {
        url: '/comment',
        templateUrl: 'templates/mine/comment.html',
        controller: 'MineCommentCtrl'
      })
      .state('mine.setting', {
        url: '/setting',
        templateUrl: 'templates/mine/setting.html',
        controller: 'MineSettingCtrl1'
      })
      .state('mine.aboutus', {
        url: '/aboutus',
        templateUrl: 'templates/mine/aboutus.html',
        controller: 'MineAboutusCtrl'
      })
      .state('mine.info', {
        url: '/info',
        templateUrl: 'templates/mine/info.html',
        controller: 'MineInfoCtrl'
      })
      .state('mine.password', {
        url: '/password',
        templateUrl: 'templates/mine/password.html',
        controller: 'MinePasswordCtrl'
      })
      .state('mine.name', {
        url: '/name',
        templateUrl: 'templates/mine/name.html',
        controller: 'MineNameCtrl'
      })
      .state('mine.address', {
        url: '/address',
        controller: 'MineAddressCtrl',
        abstract: true,
        templateUrl: 'templates/mine/address.html'
      })
      .state('mine.address.add', {
        url: '/add',
        templateUrl: 'templates/mine/address/add.html',
        controller: 'MineAddressAddCtrl'
      })
      .state('mine.address.list', {
        url: '/list',
        templateUrl: 'templates/mine/address/list.html',
        controller: 'MineAddressListCtrl'
      })


    // order part
    .state('order', {
        url: '/order',
        abstract: true,
        templateUrl: 'templates/order.html'
      })
      .state('order.list', {
        url: '/list',
        templateUrl: 'templates/order/list.html',
        controller: 'OrderListCtrl'
      })
      .state('order.cart', {
        url: '/cart',
        templateUrl: 'templates/order/cart.html',
        controller: 'OrderCartCtrl'
      })
      .state('order.chooseloc', {
        url: '/chooseloc',
        templateUrl: 'templates/order/chooseloc.html',
        controller: 'OrderChooselocCtrl'
      })
      .state('order.success', {
        url: '/success',
        templateUrl: 'templates/order/success.html',
        controller: 'OrderSuccessCtrl'
      })
      .state('order.detail', {
        url: '/:id',
        templateUrl: 'templates/order/detail.html',
        controller: 'OrderDetailCtrl'
      })
      .state('order.comment', {
        url: '/:id/comment',
        templateUrl: 'templates/order/comment.html',
        controller: 'OrderCommentCtrl'
      })

    // reg part
    .state('reg', {
      url: '/reg',
      templateUrl: 'templates/reg.html',
      controller: 'RegCtrl'
    })

    // forgot part
    .state('forgot', {
      url: '/forgot',
      templateUrl: 'templates/forgot.html',
      controller: 'ForgotCtrl'
    })

    // login part
    .state('login', {
        url: '/login',
        templateUrl: 'templates/login.html',
        controller: 'LoginCtrl'
      })
      .state('district', {
        url: '/district',
        templateUrl: 'templates/district.html',
        controller: 'DistrictCtrl'
      })
      .state('district.list', {
        url: '/list',
        views: {
          'district-left': {
            templateUrl: 'templates/district/district-left.html'
          },
          'district-right': {
            templateUrl: 'templates/district/district-right.html'
          }
        }
      })
      .state('form', {
        url: '/form',
        abstract: true,
        templateUrl: 'templates/form.html',
        controller: 'FormCtrl'
      })
      .state('form.info', {
        url: '/info/:id',
        templateUrl: 'templates/form/info.html',
        controller: 'FormInfoCtrl'
      })
      .state('form.infolist', {
        url: '/infolist',
        templateUrl: 'templates/form/infolist.html',
        controller: 'FormInfoListCtrl'
      })
      .state('form.secondhand', {
        url: '/secondhand/:id',
        templateUrl: 'templates/form/secondhand.html',
        controller: 'FormSecondHandCtrl'
      })
      .state('form.addsecond', {
        url: '/addsecond',
        templateUrl: 'templates/form/addsecond.html',
        controller: 'FormAddSecondCtrl'
      })
      .state('form.secondhandlist', {
        url: '/secondhandlist',
        templateUrl: 'templates/form/secondhandlist.html',
        controller: 'FormSecondHandListCtrl'
      })
      .state('img', {
        url: '/img/:imgurl',
        templateUrl: 'templates/img.html',
        controller: 'ImgCtrl'
      });

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/dash/home');

    // 未登录跳转管理
    $httpProvider.interceptors.push(function($rootScope, $location, $q) {
      return {
        request: function(config) {
          // console.log(config);
          if (config.url.indexOf('.html') < 0 && config.method != 'OPTIONS') {

            if ($rootScope.loadCount == 0) {
              $rootScope.$broadcast('loading:show');
              $rootScope.loadCount += 1;
            }
          }

          return config;
        },
        response: function(response) {
          // console.log(angular.toJson(response));
          if (response.status == 404) {
            $rootScope.$broadcast('loading:hide');
            $rootScope.loadCount = 0;
          }
          if (response.config.url.indexOf('.html') >= 0 || response.config.method == 'OPTIONS') {
            return response;
          }
          // console.log(response);

          // 联网loading
          $rootScope.loadCount -= 1;
          if ($rootScope.loadCount <= 0) {
            $rootScope.$broadcast('loading:hide');
            $rootScope.loadCount = 0;
          }


          if (response.data.state.code == '102') {
            $rootScope.mymessage = '请登录';

            $rootScope.$broadcast('loading:showMessage', {
              message: '请登录'
            });
            $location.path('/login');
          } else if (response.data.state.code != '200') {
            $rootScope.$broadcast('loading:showMessage', {
              message: response.data.state.message
            });
          }

          if (debug) {
            console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
            console.log(response.config.method + ' : ' + response.config.url);
            console.log(angular.toJson(response.data));
            console.log(response.data);
            console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
          }


          return response;
        },
        responseError: function(rejection) {
          // console.log(angular.toJson(rejection));
          $rootScope.$broadcast('scroll.refreshComplete');

          $rootScope.$broadcast('loading:hide');
          $rootScope.loadCount = 0;
          if (rejection.config.url.indexOf('.html') >= 0 || rejection.config.method == 'OPTIONS') {
            return rejection;
          }
          $rootScope.$broadcast('loading:showMessage', {
            message: '请求失败'
          });
          $rootScope.loadCount = 0;

          return $q.reject(rejection);
        }
      }
    });

    // 图片添加服务器地址
    $httpProvider.interceptors.push(function($rootScope, $location, $q) {
      return {
        request: function(config) {

          return config;
        },
        response: function(response) {
          // console.log(angular.toJson(response));
          if (response.status == 404) {
            $rootScope.$broadcast('scroll.refreshComplete');

            $rootScope.$broadcast('loading:hide');
            $rootScope.loadCount = 0;
          }
          if (response.config.url.indexOf('.html') >= 0 || response.config.method == 'OPTIONS') {
            return response;
          }
          // 递归设置img属性的链接为服务器链接
          var setImg = function(arr) {
            for (var i in arr) {
              // console.log(i);
              if (typeof arr[i] == 'object') {
                setImg(arr[i]);
              } else {
                if (i.indexOf('img') >= 0) {
                  if (arr[i]) {
                    // 不为空时才设置
                    if (arr[i].indexOf(server) < 0) {
                      // 判断是否是绝对路径
                      arr[i] = server + arr[i];

                    }
                  }
                }
              }
            }
          }

          var imgcount = 0;
          // 递归设置img属性的链接为服务器链接
          var setProductDetailImg = function(arr) {
            for (var i in arr) {
              // console.log(i);
              if (typeof arr[i] == 'object') {
                setProductDetailImg(arr[i]);
              } else {
                if (i == 'product_detail' && arr[i]) {
                  arr['imgcount'] = (arr[i].match(/<img/g) || []).length
                  arr[i] = arr[i].replace(/src="/g, 'src="' + server);
                  // console.log(arr[i])
                }
              }
            }
          }

          if (response.data.state.code == '200') {
            setImg(response.data.data);
            setProductDetailImg(response.data.data);
          }

          return response;
        }
      }
    });
  });
